# coding:utf-8

import xml.etree.ElementTree as ET
import requests
import traceback
from typing import List


class WebService(object):
    """使用requests POST 模拟webservice请求"""
    def __init__(self, url, send_data):
        self.url = url
        self.send_data = send_data
        self.headers = {
            # "User-Agent": "Python Post",
            "Content-type": "text/xml; charset=UTF-8",
            "Content-length": "%d" % len(self.send_data),
            "SOAPAction": ""
        }

    def send_request(self):
        """发送webservice请求，获取响应信息"""
        response = requests.post(self.url, headers=self.headers, data=self.send_data.encode("utf-8").decode("latin1"), verify=False)
        xml_data = response.content
        return xml_data

    def recv_parse(self) -> ET.Element:
        """
        1.解析响应数据：响应数据是xml格式的，这里需要解析xml获取响应数据
        2.响应数据样例：
            <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.inf.oa.ztesoft.com">
           <soapenv:Header/>
               <soapenv:Body>
                  <ser:LoginResponse>
                     <LoginReturn>{"success":true, "msg":"登录成功"}</LoginReturn>
                  </ser:LoginResponse>
               </soapenv:Body>
          </soapenv:Envelope>
        """
        return ET.fromstring(self.send_request())
        # 通过节点名称，获取响应数据
        # el_list: List[ET.Element] = dom.findall('*//returnInfo/returnCode')
        # if el_list:
        #     rtn_data = el_list[0].text
        # else:
        #     rtn_data = None
        # return rtn_data

    def main(self):
        try:
            rtn_data = self.recv_parse()
            print(rtn_data)
        except Exception as e:
            # logger.error(e.message)
            # logger.error(traceback.format_exc())
            raise
